/*
 *所有关于app_product类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*app_productService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Application.IRepositories;
using System.Collections.Generic;
using System.Net;
using VOL.Core.ManageUser;
using System;
using EFCore.BulkExtensions;
using VOL.Application.Repositories;
using VOL.Core.DBManager;
using System.Threading.Tasks;
using VOL.Core.Enums;

namespace VOL.Application.Services
{
    public partial class app_productService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Iapp_productRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public app_productService(
            Iapp_productRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();


        public async Task<app_product> GetProduct(string id)
        {
            Guid _id = Guid.Parse(id);
           return await _repository.FindAsyncFirst(it => it.Id ==_id);
        }

        public override PageGridData<app_product> GetPageData(PageDataOptions pageData)
        {

            IQueryable<app_productcolor> deptQuery = null;
            QueryRelativeList = (List<SearchParameters> parameters) =>
            {
                foreach (var item in parameters)
                {
                    if (!string.IsNullOrEmpty(item.Value) && item.Name == "ColorIds")
                    {

                        var colorids = item.Value.Split(",").Select(s => s.GetGuid()).Where(x => x != null);
                        item.Value = null;
                        deptQuery = repository.DbContext.Set<app_productcolor>().Where(x =>colorids.Contains(x.ColorId));
                    }
                }
            };

            //指定多个字段进行排序
            OrderByExpression = x => new Dictionary<object, QueryOrderBy>() {
            { x.CreateDate,QueryOrderBy.Desc },
        };

            QueryRelativeExpression = (IQueryable<app_product> queryable) =>
            {
                if (deptQuery != null)
                {
                    queryable = queryable.Where(c => deptQuery.Any(x => x.ProductId == c.Id));
                }
                return queryable;
            };

            //查询table界面显示求和
            SummaryExpress = (IQueryable<app_product> queryable) =>
            {
                return queryable.GroupBy(x => 1).Select(x => new
                {
                    //AvgPrice注意大小写和数据库字段大小写一样
                    Price = x.Sum(o => o.Price).ToString("f2")
                })
                .FirstOrDefault();
            };


            return base.GetPageData(pageData);
        }

        public override WebResponseContent Add(SaveModel saveModel)
        {
            
            //已开启事务，不要在另外开启
            base.AddOnExecuted = (app_product info, object list) =>
            {
                var deptIds = info.ColorIds?.Split(",").Select(s => s.GetGuid()).Where(x => x != null).Select(s => (Guid)s).ToArray();
                SaveColorRef(deptIds, info.Id);
                return webResponse.OK($"产品信息新建成功");
            };
            return base.Add(saveModel); ;
        }

        /// <summary>
        /// 修改产品拦截过滤
        /// 
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveModel)
        {
           
            base.UpdateOnExecuted = (app_product pro, object obj1, object obj2, List<object> List) =>
            {
                var deptIds = pro.ColorIds?.Split(",").Select(s => s.GetGuid()).Where(x => x != null).Select(s => (Guid)s).ToArray();
                SaveColorRef(deptIds, pro.Id);
                return new WebResponseContent(true);
            };
            return base.Update(saveModel);
        }

        /// <summary>
        /// 保存颜色归属
        /// </summary>
        /// <param name="deptIds"></param>
        /// <param name="userId"></param>
        public void SaveColorRef(Guid[] colorids, Guid proid)
        {

            if (proid.ToString()=="")
            {
                return;
            }
            if (colorids == null)
            {
                colorids = new Guid[] { };
            }

            var procoloridsel = repository.DbContext.Set<app_productcolor>().Where(x => x.ProductId == proid)
              .Select(s =>s.Id)
              .ToList();
            //没有设置颜色
            if (colorids.Length == 0)
            {
                return;
            }

            UserInfo user = UserContext.Current.UserInfo;
            var add = colorids.Select(s => new app_productcolor()
            {
                ColorId = s,
                ProductId = proid,
                Enable = 1,
                CreateDate = DateTime.Now,
                Creator = user.UserTrueName,
                CreateID = user.User_Id
            }).ToList();

            

            //WebResponseContent webResponse =repository.DbContextBeginTransaction(() =>
            //{
                //如果想要回滚，返回new WebResponseContent().Error("返回消息")

                app_productcolorRepository.Instance.DeleteWithKeys(procoloridsel.Cast<object>().ToArray());
                app_productcolorRepository.Instance.AddRange(add,true);
                //如果有多个批量操作时，默认SaveChanges为false，最后还是需要手动SaveChanges
                //repository.SaveChanges();
            //});
            //判断事务是否执行成功,
            //AddRange
            
        }

        public override WebResponseContent Del(object[] keys, bool delList = false)
        {
            base.DelOnExecuting = (object[] ids) =>
            {
                return webResponse.OK();
            };

            
            //清除颜色关联
            base.DelOnExecuted = (object[] ids) =>
            {
                //已刪除，无法获取记录
                //var prolst = repository.Find(x => ids.Contains(x.Id)).ToList();
                //List<Guid> lstproids = ids.Cast<Guid>().ToList();
                Guid[] guids = ids.Select(obj => Guid.Parse(obj.ToString())).ToArray();
                List<Guid> prolstids=repository.DbContext.Set<app_productcolor>().AsEnumerable().Where(it => guids.Any(x => x== it.ProductId)).Select(it=>it.Id).ToList();
                //List<Guid> prolstids = app_productcolorRepository.Instance.Find(it => prolst.Exists(x => x.Id == it.ProductId.Value)).Select(x => x.Id).ToList();//不支持
                int num=app_productcolorRepository.Instance.DeleteWithKeys(prolstids.Cast<object>().ToArray());
                return new WebResponseContent() { Status = true };
            };
            return base.Del(keys, delList);
        }
    }
}
